// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
const host = "https://ali-weather.showapi.com";
const mojiHost = "https://aliv8.mojicb.com";
const appCode = "408519e9873647689183913365546ef0";
const mojiAppCode = "408519e9873647689183913365546ef0";
const db = uniCloud.database();
const dataTimeOut = 6 * 60 * 60 * 1000;
module.exports = {
	_before: function() { // 通用预处理器
		// this.param = this.getParam();
		try {
			this.param = JSON.parse(this.getHttpInfo().body);
			console.log("_before", JSON.stringify(this.param));
		} catch (e) {
			console.log("获取参数异常:", JSON.stringify(e));
		}
	},

	/**
	 * method1方法描述
	 * @param {string} param1 参数1描述
	 * @returns {object} 返回值描述
	 */
	getMojiWeatherBy24HAnd15Days: async function(param) {
		if (!(this.param && this.param.lat && this.param.lon)) {
			if (!(param && param.lat && param.lon)) {
				return {
					errCode: 'param.lat_IS_NULL',
					errMsg: 'param.lat/lon参数不能为空'
				}
			} else {

				this.param = param;
			}
		}

		console.log("getMojiWeatherBy24HAnd15Days-location", this.param.lat + "," + this.param.lon);
		let location = new db.Geo.Point(parseFloat(this.param.lon), parseFloat(this.param.lat));
		// 查询数据库
		const w24hCollection = db.collection('HS24HCityWeather');
		let dbhWeather = await w24hCollection.where({
			"location": location
		}).get();
		//返回数据给客户端
		let hourWeather = null;
		if (dbhWeather.data && dbhWeather.data.length > 0) {
			let hour = dbhWeather.data[0];
			let time = new Date().getTime() - hour.updateTime;
			console.log("获取24小时时间差:"+time+"，updateTime:"+hour.updateTime);
			if (time < dataTimeOut) {
				hourWeather = hour.hourForecast;
				console.log("通过数据库缓存获取24小时天气");
			}
		}

		let errorCode = "";
		let city = null;
		// 数据库没查询到数据 从接口获取
		if (hourWeather == null) {
			// 获取24小时接口数据
			let hourToken = '1b89050d9f64191d494c806f78e8ea36';
			let path = '/whapi/json/aliweather/forecast24hours';

			let url = encodeURI(mojiHost + path);
			let res = await uniCloud.httpclient.request(url, {
				method: "POST",
				data: {
					'lat': this.param.lat,
					'lon': this.param.lon,
					'token': hourToken
				},
				headers: {
					"Authorization": "APPCODE " + mojiAppCode,
					"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
				},
				dataType: "json"
			});

			console.log("通过接口获取24小时天气");
			if (this.param.cityName) {
				res.data.data.city.name = this.param.cityName;
			}
			if (res.status === 200 && res.data.code === 0) {
				hourWeather = res.data.data.hourly;
				if (city === null) {
					city = res.data.data.city;
				}
				let nowDay = new Date();
				// 有原始数据更新
				if (dbhWeather.data && dbhWeather.data.length > 0) {
					w24hCollection.where({
						"location": location
					}).update({
						"updateTime": nowDay.getTime(),
						"cityName": res.data.data.city.name,
						"city": res.data.data.city,
						"hourForecast": res.data.data.hourly,
						"nowdate": nowDay.getFullYear() + nowDay.getMonth() + nowDay.getDay() + nowDay
							.getHours() + nowDay.getMinutes() + nowDay.getSeconds()
					});
				} else { // 没有原始数据增加
					w24hCollection.add({
						"location": location,
						"updateTime": nowDay.getTime(),
						"cityName": res.data.data.city,
						"city": res.data.data.city,
						"hourForecast": res.data.data.hourly,
						"nowdate": nowDay.getFullYear() + nowDay.getMonth() + nowDay.getDay() + nowDay
							.getHours() + nowDay.getMinutes() + nowDay.getSeconds()
					})
				}
			} else {
				errorCode = "" + res.status;
			}
		}

		// 获取40day接口数据
		// 查询数据库
		const dayCollection = db.collection('HS15DayCityWeather');
		let dbDayWeather = await dayCollection.where({
			"location": location
		}).get();
		//返回数据给客户端
		let dayWeather = null;
		if (dbDayWeather.data && dbDayWeather.data.length > 0) {
			let day = dbDayWeather.data[0];
			let time = new Date().getTime() - day.updateTime;
			console.log("获取15天天气时间差:"+time +"，updateTime:"+day.updateTime);
			if (time < dataTimeOut) {
				dayWeather = day.dayForecast;
				console.log("通过缓存获取15天小时天气");
			}
		}

		if (dayWeather == null) {
			let dayToken = '7538f7246218bdbf795b329ab09cc524';
			let dayPath = '/whapi/json/aliweather/forecast15days';


			let dayUrl = encodeURI(mojiHost + dayPath);
			let dayRes = await uniCloud.httpclient.request(dayUrl, {
				method: "POST",
				data: {
					'lat': this.param.lat,
					'lon': this.param.lon,
					'token': dayToken
				},
				headers: {
					"Authorization": "APPCODE " + mojiAppCode,
					"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
				},
				dataType: "json"
			});
			console.log("通过接口获取15天小时天气");
			if (this.param.cityName) {
				dayRes.data.data.city.name = this.param.cityName;
			}
			if (dayRes.status === 200 && dayRes.data.code === 0) {
				dayWeather = dayRes.data.data.forecast;
				if (city === null) {
					city = dayRes.data.data.city;
				}
				let nowDay = new Date();
				// 有原始数据更新
				if (dbDayWeather.data && dbDayWeather.data.length > 0) {
					dayCollection.where({
						"location": location
					}).update({
						"updateTime": new Date().getTime(),
						"cityName": dayRes.data.data.city.name,
						"city": dayRes.data.data.city,
						// 删除第一天数据
						"dayForecast": dayRes.data.data.forecast.shift(),
						"nowdate": nowDay.getFullYear() + nowDay.getMonth() + nowDay.getDay() + nowDay
							.getHours() + nowDay.getMinutes() + nowDay.getSeconds()
					});
				} else { // 没有原始数据增加
					dayCollection.add({
						"location": location,
						"updateTime": new Date().getTime(),
						"cityName": dayRes.data.data.city.name,
						"city": dayRes.data.data.city,
						"dayForecast": dayRes.data.data.forecast.shift(),
						"nowdate": nowDay.getFullYear() + nowDay.getMonth() + nowDay.getDay() + nowDay
							.getHours() + nowDay.getMinutes() + nowDay.getSeconds()
					})
				}
			} else {
				errorCode = errorCode + "," + res.status;
			}
		}


		/*
		 "city": {
		      "cityId": 284609,
		      "counname": "中国",
		      "name": "东城区",
		      "pname": "北京市"
		    }
		*/

		// console.log("getHourWeather", JSON.stringify(hourWeather));
		// console.log("getDayWeather", JSON.stringify(dayWeather));
		if (city) {
			city.lat = "" + this.param.lat;
			city.lon = "" + this.param.lon;
		}
		if (hourWeather && dayWeather) {
			return {
				'statusCode': 200,
				// 'cityName': this.param.cityName,
				'city': city,
				"daysWeather": dayWeather,
				"hoursWeather": hourWeather,
			};
		} else {
			return {
				errCode: errorCode,
				errMsg: '请求异常'
			}
		}
	},

	// 获取天气生活指数
	getMojiWeatherIndex: async function(param) {
		if (!(this.param && this.param.lat && this.param.lon)) {
			if (!(param && param.lat && param.lon)) {
				return {
					errCode: 'param.lat_IS_NULL',
					errMsg: 'param.lat/lon参数不能为空'
				}
			} else {
				this.param = param;
			}
		}

		// 获取24小时接口数据
		let aqiToken = '42b0c7e2e8d00d6e80d92797fe5360fd';
		let path = '/whapi/json/aliweather/index';
		let url = encodeURI(mojiHost + path);
		let res = await uniCloud.httpclient.request(url, {
			method: "POST",
			data: {
				'lat': this.param.lat,
				'lon': this.param.lon,
				'token': aqiToken
			},
			headers: {
				"Authorization": "APPCODE " + mojiAppCode,
				"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
			},
			dataType: "json"
		});

		console.log("getMojiWeatherAlert", url + JSON.stringify(res));
		if (this.param.cityName) {
			res.data.data.city.name = this.param.cityName;
		}
		if (res.status === 200 && res.data.code === 0) {
			return {
				'statusCode': 200,
				'city': res.data.data.city,
				"alert": res.data.data.alert,
			};
		} else {
			return {
				errCode: '' + res.status,
				errMsg: '请求异常'
			}
		}
	},

	/*
	"alert": [
	      {
	        "content": "广州市气象局于09月01日17时28分发布雷雨大风蓝色预警信号，请注意防御。",
	        "infoid": 70,
	        "level": "蓝色",
	        "name": "雷雨大风",
	        "pub_time": "2016-09-01 17:46:06",
	        "title": "广东省广州市气象台发布蓝色雷雨大风预警",
	        "type": "雷雨大风蓝色"
	      }
	    ],
	*/
	// 获取天气预警
	getMojiWeatherAlert: async function(param) {
		if (!(this.param && this.param.lat && this.param.lon)) {
			if (!(param && param.lat && param.lon)) {
				return {
					errCode: 'param.lat_IS_NULL',
					errMsg: 'param.lat/lon参数不能为空'
				}
			} else {
				this.param = param;
			}
		}

		let location = new db.Geo.Point(parseFloat(this.param.lon), parseFloat(this.param.lat));
		// 查询数据库
		const dbCollection = db.collection('HSMojiWeatherAlert');
		let dbhWeather = await dbCollection.where({
			"location": location
		}).get();
		//返回数据给客户端
		let result = null;
		let errorCode = "";
		let city = null;
		if (dbhWeather.data && dbhWeather.data.length > 0) {
			let firstValue = dbhWeather.data[0];
			if (firstValue.updateTime - new Date().getTime() < dataTimeOut) {
				result = firstValue.alert;
			}
		}

		// 数据库没查询到数据 从接口获取
		if (result == null) {
			// 获取24小时接口数据
			let aqiToken = 'd01246ac6284b5a591f875173e9e2a18';
			let path = '/whapi/json/aliweather/alert';
			let url = encodeURI(mojiHost + path);
			let res = await uniCloud.httpclient.request(url, {
				method: "POST",
				data: {
					'lat': this.param.lat,
					'lon': this.param.lon,
					'token': aqiToken
				},
				headers: {
					"Authorization": "APPCODE " + mojiAppCode,
					"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
				},
				dataType: "json"
			});
			let nowDay = new Date();
			console.log("getMojiWeatherAlert", url + JSON.stringify(res));
			if (this.param.cityName) {
				res.data.data.city.name = this.param.cityName;
			}
			if (res.status === 200 && res.data.code === 0) {
				city = res.data.data.city;
				result = res.data.data.alert;
				if (result) {
					// 有原始数据更新
					if (dbhWeather.data && dbhWeather.data.length > 0) {
						dbCollection.where({
							"location": location
						}).update({
							"updateTime": new Date().getTime(),
							"cityName": res.data.data.city.name,
							'city': res.data.data.city,
							"alert": res.data.data.alert,
							"nowdate": nowDay.getFullYear() + nowDay.getMonth() + nowDay.getDay() + nowDay
								.getHours() + nowDay.getMinutes() + nowDay.getSeconds()
						});
					} else { // 没有原始数据增加
						dbCollection.add({
							"location": location,
							"updateTime": new Date().getTime(),
							"cityName": res.data.data.city.name,
							'city': res.data.data.city,
							"alert": res.data.data.alert,
							"nowdate": nowDay.getFullYear() + nowDay.getMonth() + nowDay.getDay() + nowDay
								.getHours() + nowDay.getMinutes() + nowDay.getSeconds()
						})
					}
				}
			} else {
				errorCode = res.status;
			}
		}

		if (result) {
			return {
				'statusCode': 200,
				'city': city,
				"cityName": city.name,
				"alert": result,
			};
		} else {
			if (errorCode === "") {
				return {
					errCode: errorCode,
					errMsg: '请求异常'
				}
			} else {
				return {
					errCode: errorCode,
					errMsg: '暂无数据'
				}
			}
		}
	},
	// 空气质量指数
	getMojiWeatherAQI: async function(param) {

		if (!(this.param && this.param.lat && this.param.lon)) {
			if (!(param && param.lat && param.lon)) {
				return {
					errCode: 'param.lat_IS_NULL',
					errMsg: 'param.lat/lon参数不能为空'
				}
			} else {
				this.param = param;
			}
		}

		let location = new db.Geo.Point(parseFloat(this.param.lon), parseFloat(this.param.lat));
		// 查询数据库
		const dbCollection = db.collection('HSMojiWeatherAQI');
		let dbhWeather = await dbCollection.where({
			"location": location
		}).get();
		//返回数据给客户端
		let result = null;
		let errorCode = "";
		let city = null;
		if (dbhWeather.data && dbhWeather.data.length > 0) {
			let firstValue = dbhWeather.data[0];
			if (firstValue.updateTime - new Date().getTime() < dataTimeOut) {
				result = firstValue.aqi;
			}
		}

		if (result === null) {
			// 获取24小时接口数据
			let aqiToken = '6e9a127c311094245fc1b2aa6d0a54fd';
			let path = '/whapi/json/aliweather/aqi';
			let url = encodeURI(mojiHost + path);
			let res = await uniCloud.httpclient.request(url, {
				method: "POST",
				data: {
					'lat': this.param.lat,
					'lon': this.param.lon,
					'token': aqiToken
				},
				headers: {
					"Authorization": "APPCODE " + mojiAppCode,
					"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
				},
				dataType: "json"
			});

			console.log("getMojiWeatherAQI", url + JSON.stringify(res));
			if (this.param.cityName) {
				res.data.data.city.name = this.param.cityName;
			}
			let nowDay = new Date();	
			if (res.status === 200 && res.data.code === 0) {
				city = res.data.data.city;
				result = res.data.data.aqi;
				if (result) {
					// 有原始数据更新
					if (dbhWeather.data && dbhWeather.data.length > 0) {
						dbCollection.where({
							"location": location
						}).update({
							"updateTime": new Date().getTime(),
							"cityName": res.data.data.city.name,
							'city': res.data.data.city,
							"alert": res.data.data.aqi,
							"nowdate": nowDay.getFullYear() + nowDay.getMonth() + nowDay.getDay() + nowDay
								.getHours() + nowDay.getMinutes() + nowDay.getSeconds()
						});
					} else { // 没有原始数据增加
						dbCollection.add({
							"location": location,
							"updateTime": new Date().getTime(),
							"cityName": res.data.data.city.name,
							'city': res.data.data.city,
							"alert": res.data.data.aqi,
							"nowdate": nowDay.getFullYear() + nowDay.getMonth() + nowDay.getDay() + nowDay
								.getHours() + nowDay.getMinutes() + nowDay.getSeconds()
						})
					}
				}
			} else {
				errorCode = res.status;
			}
		}

		if (result != null) {
			return {
				'statusCode': 200,
				'city': city,
				"cityName": city.name,
				"aqi": result,
			};
		} else {
			if (errorCode === "") {
				return {
					errCode: errorCode,
					errMsg: '请求异常'
				}
			} else {
				return {
					errCode: errorCode,
					errMsg: '暂无数据'
				}
			}
		}

	},
	getMojiWeatherBy24H: async function(param) {
		if (!param || !param.lat || !param.lon) {
			return {
				errCode: 'param.lat_IS_NULL',
				errMsg: 'param.lat/lon参数不能为空'
			}
		}
		// 获取24小时接口数据
		let hourToken = '1b89050d9f64191d494c806f78e8ea36';
		let path = '/whapi/json/aliweather/forecast24hours';


		let url = encodeURI(mojiHost + path);
		let res = await uniCloud.httpclient.request(url, {
			method: "POST",
			data: {
				'lat': param.lat,
				'lon': param.lon,
				'token': hourToken
			},
			headers: {
				"Authorization": "APPCODE " + mojiAppCode,
				"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
			},
			dataType: "json"
		});

		console.log("getWeatherBy24H", url + JSON.stringify(res));
	},


	getMojiWeatherBy15Days: async function(param) {
		if (!param || !param.lat || !param.lon) {
			return {
				errCode: 'param.lat_IS_NULL',
				errMsg: 'param.lat/lon参数不能为空'
			}
		}
		// 获取24小时接口数据
		let dayToken = '7538f7246218bdbf795b329ab09cc524';
		let path = '/whapi/json/aliweather/forecast15days';


		let url = encodeURI(mojiHost + path);
		let res = await uniCloud.httpclient.request(url, {
			method: "POST",
			data: {
				'lat': param.lat,
				'lon': param.lon,
				'token': dayToken
			},
			headers: {
				"Authorization": "APPCODE " + mojiAppCode,
				"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
			},
			dataType: "json"
		});

		console.log("getMojiWeatherBy15Days", url + JSON.stringify(res));
	},


	getWeatherBy24HAnd40Days: async function(param) {
		let cityName = "";
		// if(param){
		// 	cityName = param.cityName;
		// }else{
		if (!this.param || !this.param.cityName) {
			return {
				errCode: 'cityName_IS_NULL',
				errMsg: 'cityName参数不能为空'
			}
		} else {
			cityName = this.param.cityName;
		}
		const collection = db.collection('HighSpeedWeather24H');
		let list = await collection.where({
			"typeId": event.typeId
		}).get();
		// }
		// 获取24小时接口数据
		let query = "area=" + cityName;
		let path = '/hour24' + '?' + query;


		let url = encodeURI(host + path);
		let res = await uniCloud.httpclient.request(url, {
			method: "GET",
			headers: {
				"Authorization": "APPCODE " + appCode
			},
			dataType: "json"
		});

		console.log("getWeatherBy24H", url + JSON.stringify(res));
		// 获取40day接口数据
		let query2 = "area=" + cityName;
		let path2 = '/day40' + '?' + query2;
		let url2 = encodeURI(host + path2);
		let res2 = await uniCloud.httpclient.request(url2, {
			method: "GET",
			headers: {
				"Authorization": "APPCODE " + appCode
			},
			dataType: "json"
		});
		console.log("getWeatherBy40Day", url2 + JSON.stringify(res2));
		if (res.status === 200 && res2.status === 200) {
			return {
				'statusCode': res.status,
				'city': cityName,
				"weather": {
					"daysWeather": res2.data.showapi_res_body.day40List,
					"hoursWeather": res.data.showapi_res_body.hourList
				}
			};
		} else {
			return {
				errCode: '' + res.status,
				errMsg: '请求异常'
			}
		}

	},

	getWeatherBy24H: async function(param) {
		let cityName = "";
		// if(param){
		// 	cityName = param.cityName;
		// }else{
		if (!this.param || !this.param.cityName) {
			return {
				errCode: 'cityName_IS_NULL',
				errMsg: 'cityName参数不能为空'
			}
		} else {
			cityName = this.param.cityName;
		}
		// }

		let query = "area=" + cityName;
		let path = '/hour24' + '?' + query;

		let url = encodeURI(host + path);
		let res = await uniCloud.httpclient.request(url, {
			method: "GET",
			headers: {
				"Authorization": "APPCODE " + appCode
			},
			dataType: "json"
		});
		console.log("getWeatherBy24H", url + JSON.stringify(res));
		if (res.status === 200) {
			return res.data;
		} else {
			return {
				errCode: '' + res.status,
				errMsg: '请求异常'
			}
		}

	},
	getWeatherBy15Days: async function(param) {
		let cityName = "";
		// if(param){
		// 	cityName = param.cityName;
		// }else{
		if (!this.param || !this.param.cityName) {
			return {
				errCode: 'cityName_IS_NULL',
				errMsg: 'cityName参数不能为空'
			}
		} else {
			cityName = this.param.cityName;
		}
		// }

		let query = "area=" + cityName;
		let path = '/day15' + '?' + query;

		let url = encodeURI(host + path);
		let res = await uniCloud.httpclient.request(url, {
			method: "GET",
			headers: {
				"Authorization": "APPCODE " + appCode
			},
			dataType: "json"
		});
		if (res.status === 200) {
			return res.data;
		} else {
			return {
				errCode: '' + res.status,
				errMsg: '请求异常'
			}
		}
	},
	getWeatherBy40Days: async function(param) {
		let cityName = "";
		// if(param){
		// 	cityName = param.cityName;
		// }else{
		if (!this.param || !this.param.cityName) {
			return {
				errCode: 'cityName_IS_NULL',
				errMsg: 'cityName参数不能为空'
			}
		} else {
			cityName = this.param.cityName;
		}
		// }

		let query = "area=" + cityName;
		let path = '/day40' + '?' + query;

		let url = encodeURI(host + path);
		let res = await uniCloud.httpclient.request(url, {
			method: "GET",
			headers: {
				"Authorization": "APPCODE " + appCode
			},
			dataType: "json"
		});
		if (res.status === 200) {
			return res.data;
		} else {
			return {
				errCode: '' + res.status,
				errMsg: '请求异常'
			}
		}
	},
	getHistoryWeather: async function(param) {
		let cityName = "";
		let month = "";
		// if(param){
		// 	cityName = param.cityName;
		// 	month = param.month;
		// }else{
		if (!this.param || !this.param.cityName) {
			return {
				errCode: 'cityName_IS_NULL',
				errMsg: 'cityName参数不能为空'
			}
		} else {
			cityName = this.param.cityName;
			month = this.param.month;
		}
		// }

		let query = "area=" + cityName + "&month=" + month;
		let path = '/weatherhistory' + '?' + query;
		let url = encodeURI(host + path);
		let res = await uniCloud.httpclient.request(url, {
			method: "GET",
			headers: {
				"Authorization": "APPCODE " + appCode
			},
			dataType: "json"
		});
		if (res.status === 200) {
			return res.data;
		} else {
			return {
				errCode: '' + res.status,
				errMsg: '请求异常'
			}
		}
	},
}